<style lang="less">
.article-list {
  .article-list-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px 0px;
  }

  .article-list-title {
    margin: 0;
    color: #303133;
  }

  .article-list-footer {
    margin-top: 15px;
    text-align: right;
  }

  .date-time {
    line-height: 1.5;
    white-space: pre-line;
  }

  .tag-group {
    .el-tag {
      margin-right: 8px;

      &:last-child {
        margin-right: 0;
      }
    }
  }

  .search-box {
    margin: 0;
  }
}
</style>
<template>
  <div class="article-list">
    <div class="article-list-header">
      <h3 class="article-list-title">文章列表</h3>
      <div class="search-box">
        <el-input v-model="search" size="small" placeholder="输入关键字搜索（标题或作者）" clearable @clear="handleSearchClear"
          @keyup.enter.native="handleSearch" style="width: 300px;">
          <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
        </el-input>
      </div>
    </div>
    <div class="article-list-wrap">
      <el-table :data="tableData" style="width: 100%" border>
        <el-table-column label="序号" width="80" align="center">
          <template slot-scope="scope">
            <span>{{ scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="标题" prop="title" show-overflow-tooltip></el-table-column>
        <el-table-column label="作者" prop="author" width="100"></el-table-column>
        <el-table-column label="日期" width="150">
          <template slot-scope="scope">
            <div class="date-time">{{ formatDateTime(scope.row.createAt) }}</div>
          </template>
        </el-table-column>
        <el-table-column label="导航分类" width="150">
          <template slot-scope="scope">
            <div class="tag-group">
              <el-tag size="small">{{ scope.row.cate }}</el-tag>
              <el-tag size="small" type="info">{{ scope.row.cate_name }}</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100" align="center">
          <template slot-scope="scope">
            <el-tag
              :type="scope.row.status === 'published' ? 'success' : scope.row.status === 'draft' ? 'warning' : 'info'"
              size="small">
              {{ scope.row.status === 'published' ? '已发布' : scope.row.status === 'draft' ? '草稿' : '已下架' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="浏览量" width="100" align="center" prop="view_count"></el-table-column>
        <el-table-column label="是否置顶" width="80" align="center">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.is_top == 1" type="danger" size="small">是</el-tag>
            <span v-else>否</span>
          </template>
        </el-table-column>
        <el-table-column label="标签" prop="tag" show-overflow-tooltip align="center"></el-table-column>
        <el-table-column label="操作" align="center" width="200">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">查看详情</el-button>
            <el-button v-if="isAdmin" size="mini" type="danger"
              @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="article-list-footer">
      <el-pagination @current-change="currentChangeFn" background layout="prev, pager, next" :page-size="page_size"
        :pager-count="7" :total="total">
      </el-pagination>
    </div>
  </div>
</template>

<script>
import { itemsArticle, deleteArticle, searchArticle, getCurrentUserDetail } from "../../api/index"
import { requireLogin } from "../../utils/auth"

export default {
  data() {
    return {
      tableData: [],
      search: '',
      page_num: 1,
      page_size: 5,
      total: 0,
      currentUserId: null // 当前登录用户的id
    }
  },
  computed: {
    // 判断是否为管理员
    isAdmin() {
      const role = localStorage.getItem("USER_ROLE")
      return role === '1'
    }
  },
  methods: {
    // 格式化日期时间
    formatDateTime(dateTimeStr) {
      if (!dateTimeStr) return ''
      const date = new Date(dateTimeStr)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      const seconds = String(date.getSeconds()).padStart(2, '0')
      return `${year}-${month}-${day}\n${hours}:${minutes}:${seconds}`
    },
    // 编辑文章
    async handleEdit(index, row) {
      const isLoggedIn = await requireLogin()
      if (!isLoggedIn) {
        const result = await this.$showLoginPrompt()
        if (result.isConfirmed) {
          this.$router.push({ path: "/login" })
        }
        return
      }
      // 判断是否为文章作者或管理员
      const isAuthor = this.currentUserId && row.user_id && String(this.currentUserId) === String(row.user_id)
      const canEdit = isAuthor || this.isAdmin
      // 如果可以编辑，正常跳转；否则传递readonly参数
      this.$router.push({
        path: '/edit_article',
        query: { id: row.id, readonly: canEdit ? undefined : 'true' }
      })
    },
    // 删除文章
    async handleDelete(index, row) {
      const isLoggedIn = await requireLogin()
      if (!isLoggedIn) {
        const result = await this.$showLoginPrompt()
        if (result.isConfirmed) {
          this.$router.push({ path: "/login" })
        }
        return
      }

      const result = await this.$showConfirm('提示', '您确定要删除这篇文章吗？', '确定', '取消')
      if (result.isConfirmed) {
        this.deleteArticleFn(row.id)
      }
    },
    // 分页变化处理
    currentChangeFn(index) {
      this.page_num = index
      // 如果有搜索关键词，执行搜索，否则加载列表
      if (this.search && this.search.trim()) {
        this.searchArticleFn()
      } else {
        this.itemsArticleFn()
      }
    },
    // 获取文章列表
    async itemsArticleFn() {
      let page_num = this.page_num
      let page_size = this.page_size
      await itemsArticle({ page_num, page_size })
        .then(resData => {
          if (resData.code == 200) {
            // 处理数据格式，可能是 resData.data 或 resData.result
            this.tableData = resData.data || resData.result || []
            this.total = resData.total || 0
          } else {
            this.tableData = []
            this.total = 0
          }
        })
        .catch(err => {
          console.error('获取文章列表失败:', err)
          this.tableData = []
          this.total = 0
        })
    },
    // 搜索文章
    async searchArticleFn() {
      const keyword = this.search ? this.search.trim() : ''
      if (!keyword) {
        // 如果关键词为空，加载普通列表
        this.itemsArticleFn()
        return
      }

      await searchArticle({ keyword })
        .then(resData => {
          // 搜索接口返回格式：{ result: [...], msg: "搜索文章成功" }
          // 或者可能是 { code: 200, result: [...], msg: "..." }
          if (resData.result) {
            const searchResults = Array.isArray(resData.result) ? resData.result : []
            this.tableData = searchResults
            this.total = searchResults.length
          } else if (resData.code == 200 && resData.data) {
            const searchResults = Array.isArray(resData.data) ? resData.data : []
            this.tableData = searchResults
            this.total = searchResults.length
          } else {
            this.tableData = []
            this.total = 0
          }
        })
        .catch(err => {
          console.error('搜索文章失败:', err)
          this.tableData = []
          this.total = 0
          this.$showError && this.$showError('搜索失败', '搜索文章时发生错误，请重试')
        })
    },
    // 删除文章
    async deleteArticleFn(id) {
      const isLoggedIn = await requireLogin()
      if (!isLoggedIn) {
        const result = await this.$showLoginPrompt()
        if (result.isConfirmed) {
          this.$router.push({ path: "/login" })
        }
        return
      }

      let token = localStorage.getItem("AUTO_TOKEN")
      await deleteArticle({ token, id })
        .then(resData => {
          if (resData.code == 200) {
            this.$showSuccess('成功', resData.msg || '删除成功')
            this.itemsArticleFn()
          } else {
            this.$showError('失败', resData.msg || '删除失败')
          }
        })
        .catch(() => {
          this.$showError('失败', '删除失败，请重试')
        })
    },
    // 搜索处理
    handleSearch() {
      this.page_num = 1
      const keyword = this.search ? this.search.trim() : ''
      if (keyword) {
        this.searchArticleFn()
      } else {
        this.itemsArticleFn()
      }
    },
    // 清空搜索
    handleSearchClear() {
      this.search = ''
      this.page_num = 1
      this.itemsArticleFn()
    },
    // 加载当前用户id
    async loadCurrentUserId() {
      const token = localStorage.getItem("AUTO_TOKEN")
      if (token) {
        try {
          const resData = await getCurrentUserDetail()
          if (resData && resData.code === 200 && resData.data) {
            this.currentUserId = resData.data.id
          }
        } catch (error) {
          console.error('获取用户信息失败:', error)
        }
      }
    }
  },
  async created() {
    // 获取当前用户id
    await this.loadCurrentUserId()
    this.itemsArticleFn()
    this.$store.commit("addTab", this.$route)
  },
  watch: {
    $route: {
      immediate: true,
      deep: true,
      handler(newRoute) {
        this.$store.commit("addTab", newRoute)
      }
    }
  }
}
</script>
